package com.example.shipback.utils;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;

/**
 * @author Emil
 */
public class WebSocketUtils {
    private static WebSocketSession session; // 保存WebSocketSession对象

    public static void sendMessage(String url, String message) throws URISyntaxException, InterruptedException {
        // 创建WebSocket客户端
        StandardWebSocketClient client = new StandardWebSocketClient();
        // 计数器，用于等待连接完成
        CountDownLatch latch = new CountDownLatch(1);

        // 连接并添加处理器
        client.doHandshake(new TextWebSocketHandler() {
            @Override
            public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
                System.out.println("Connected to the server");
                session = webSocketSession; // 保存WebSocketSession对象
                session.sendMessage(new TextMessage(message));
            }

            @Override
            protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
                System.out.println("Received message from server: " + message.getPayload());
                latch.countDown(); // 收到消息后，递减计数器
            }

            @Override
            public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
                System.out.println("Connection closed: " + status);
            }
        }, new WebSocketHttpHeaders(), new URI(url));

        latch.await(); // 等待消息接收
        // 模拟某个条件下断开连接
        disconnectWebSocket(); // 调用断开连接的方法
    }

    public static void disconnectWebSocket() {
        if (session != null && session.isOpen()) {
            try {
                session.close(); // 调用WebSocketSession的close()方法断开连接
                System.out.println("WebSocket connection closed.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("WebSocket is already closed or not connected.");
        }
    }
}
